package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.bean.UserBean;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import logic.bean.CouponInfo;
import logic.constants.Const;
import logic.dao.UserDao;
import logic.util.DateUtil;
import logic.util.Util;
import logic.util.Utils;


/**
 * OrderMenuMyCouponActivity
 *
 * @Description：我的代金券界面
 * @Author：zhangdong
 * @Date：2015年7月13日下午17:27:32
 */
public class OrderMenuMyCouponActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener {
    private final static int TAB_UNUSED = 0;
    private final static int TAB_USED = 1;
    private final static int TAB_OUT_TIME = 2;
    private Context context;
    private LoadingView loadingView;
    private TextView tvTitle, tvUnused, tvUsed, tvOutTime, tvNone;
    private Button btnBack, btnExchange;
    private LinearLayout llNone, llExchange;
    private EditText etExchange;
    private ListView listView;
    private List<CouponInfo> listCoupons = new ArrayList<CouponInfo>();
    private List<CouponInfo> data = new ArrayList<CouponInfo>();
    private MyAdapter adapter = new MyAdapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.om_my_coupon);
        this.context = this;
        initView();
        initLoadingView();
        initData();
        setListener();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

            }
        }
    };

    private void setListener() {
        btnBack.setOnClickListener(this);
        btnExchange.setOnClickListener(this);
        tvUnused.setOnClickListener(this);
        tvUsed.setOnClickListener(this);
        tvOutTime.setOnClickListener(this);
    }

    private void initLoadingView() {
        loadingView.setLoadingAnim(R.drawable.home_progress);
        loadingView.changeLoadingStatus(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("我的代金券");
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);

        loadingView = (LoadingView) findViewById(R.id.order_loading_view);
        llNone = (LinearLayout) findViewById(R.id.ll_om_my_coupon_none);
        tvNone = (TextView) findViewById(R.id.tv_om_my_coupon_none);
        loadingView.setVisibility(View.VISIBLE);
        llNone.setVisibility(View.GONE);

        llExchange = (LinearLayout) findViewById(R.id.ll_om_my_coupon_exchange);
        etExchange = (EditText) findViewById(R.id.et_om_my_coupon_exchange);
        btnExchange = (Button) findViewById(R.id.btn_om_my_coupon_exchange);

        tvUnused = (TextView) findViewById(R.id.tv_om_my_coupon_unused);
        tvUsed = (TextView) findViewById(R.id.tv_om_my_coupon_used);
        tvOutTime = (TextView) findViewById(R.id.tv_om_my_coupon_out_time);

        listView = (ListView) findViewById(R.id.lv_om_my_coupon);
        listView.setVisibility(View.GONE);
    }

    private void initData() {
        listView.setAdapter(adapter);
//		setSelected(TAB_UNUSED);
        if (Util.isEmpty(Const.phone_number)) {
            UserBean user = UserDao.getInstance(this).getLastLoginUser();
            Const.phone_number = user.getAccount();
            Const.login_key = user.getKey();
            NewActionHelp.setAccount(Const.phone_number);
            NewActionHelp.setLoginKey(Const.login_key);
        }
        NewActionHelp.qryUserVoucherList(context, 0, new QryCouponsHandler());
    }

    private void setVisible() {
        if (data == null || data.size() == 0) {
            listView.setVisibility(View.GONE);
            llNone.setVisibility(View.VISIBLE);
        } else {
            listView.setVisibility(View.VISIBLE);
            llNone.setVisibility(View.GONE);
        }
    }

    private void setSelected(int key) {
        data.clear();
        switch (key) {
            case TAB_UNUSED:
                tvUnused.setSelected(true);
                tvUsed.setSelected(false);
                tvOutTime.setSelected(false);
                data.addAll(statusFilter(sortByTime(2), 1));
                tvNone.setText("暂无未使用的代金券");
                setVisible();
                break;
            case TAB_USED:
                tvUnused.setSelected(false);
                tvUsed.setSelected(true);
                tvOutTime.setSelected(false);
                data.addAll(statusFilter(sortByTime(1), 2));
                tvNone.setText("暂无已使用的代金券");
                setVisible();
                break;
            case TAB_OUT_TIME:
                tvUnused.setSelected(false);
                tvUsed.setSelected(false);
                tvOutTime.setSelected(true);
                data.addAll(statusFilter(listCoupons, 3));
                tvNone.setText("暂无已过期的代金券");
                setVisible();
                break;
        }
        adapter.notifyDataSetChanged();
    }

    private class QryCouponsHandler
            extends
            ObjectHttpResponseHandler<List<CouponInfo>> {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode < 1000) {
                Utils.ToastShow(context, "网络错误");
            } else {
                Utils.ToastShow(context, "请求出错");
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<CouponInfo> object, String responseString) {
            Log.i(responseString);
            loadingView.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            //测试数据
//			if (object == null || object.size() == 0)
//			{
//				try
//				{
//					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//					CouponInfo info1 = new CouponInfo();
//					info1.setCardName("100元代金券");
//					info1.setValidityStartTime(sdf.parse("2015-07-01").getTime());
//					info1.setValidityEndTime(sdf.parse("2015-10-11").getTime());
//					info1.setStatus(1);
//					object.add(info1);
//					CouponInfo info2 = new CouponInfo();
//					info2.setCardName("100元代金券");
//					info2.setValidityStartTime(sdf.parse("2015-07-02").getTime());
//					info2.setValidityEndTime(sdf.parse("2015-08-12").getTime());
//					info2.setUseTime(sdf.parse("2015-07-13").getTime());
//					info2.setStatus(2);
//					object.add(info2);
//					CouponInfo info3 = new CouponInfo();
//					info3.setCardName("100元代金券");
//					info3.setValidityStartTime(sdf.parse("2015-07-01").getTime());
//					info3.setValidityEndTime(sdf.parse("2015-07-11").getTime());
//					info3.setStatus(3);
//					object.add(info3);
//					CouponInfo info4 = new CouponInfo();
//					info4.setCardName("100元代金券");
//					info4.setValidityStartTime(sdf.parse("2015-06-01").getTime());
//					info4.setValidityEndTime(sdf.parse("2015-08-30").getTime());
//					info4.setStatus(1);
//					object.add(info4);
//					CouponInfo info5 = new CouponInfo();
//					info5.setCardName("100元代金券");
//					info5.setValidityStartTime(sdf.parse("2015-07-02").getTime());
//					info5.setValidityEndTime(sdf.parse("2015-08-12").getTime());
//					info5.setUseTime(sdf.parse("2015-07-21").getTime());
//					info5.setStatus(2);
//					object.add(info5);
//					CouponInfo info6 = new CouponInfo();
//					info6.setCardName("100元代金券");
//					info6.setValidityStartTime(sdf.parse("2015-07-01").getTime());
//					info6.setValidityEndTime(sdf.parse("2015-07-12").getTime());
//					info6.setStatus(3);
//					object.add(info6);
//				}
//				catch (Exception e)
//				{
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
            listCoupons.clear();
            listCoupons.addAll(object);
            setSelected(TAB_UNUSED);
        }

        @Override
        public Type getType() {
            return new TypeToken<List<CouponInfo>>() {
            }.getType();
        }
    }

    /**
     * status: 1=未使用 2=已使用 3=已过期
     */
    private List<CouponInfo> statusFilter(List<CouponInfo> data, int status) {
        List<CouponInfo> newData = new ArrayList<CouponInfo>();
        for (CouponInfo info : data) {
            if (info.getStatus() == status) {
                newData.add(info);
            }
        }
        return newData;
    }

    private List<CouponInfo> sortByTime(final int timeType) {
        class RecentTimeComparator
                implements
                Comparator<CouponInfo> {

            @Override
            public int compare(CouponInfo lhs, CouponInfo rhs) {
                int result = 0;
                if (timeType == 0) {
                    result = rhs.getValidityStartTime() - lhs.getValidityStartTime() > 0 ? 1 : -1;
                } else if (timeType == 1) {
                    result = rhs.getUseTime() - lhs.getUseTime() > 0 ? 1 : -1;
                } else if (timeType == 2) {
                    result = rhs.getValidityEndTime() - lhs.getValidityEndTime() < 0 ? 1 : -1;
                } else if (timeType == 3) {
                    result = rhs.getDispatchTime() - lhs.getDispatchTime() > 0 ? 1 : -1;
                }
                return result;
            }

        }
        List<CouponInfo> newData = new ArrayList<CouponInfo>();
        newData.clear();
        newData.addAll(listCoupons);
        Collections.sort(newData, new RecentTimeComparator());
        return newData;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                Util.hideInputMethodManager(context, etExchange);
                onBackPressed();
                this.finish();
                break;
            case R.id.btn_om_my_coupon_exchange:
                Util.hideInputMethodManager(context, etExchange);
                break;
            case R.id.tv_om_my_coupon_unused:
                setSelected(TAB_UNUSED);
                break;
            case R.id.tv_om_my_coupon_used:
                setSelected(TAB_USED);
                break;
            case R.id.tv_om_my_coupon_out_time:
                setSelected(TAB_OUT_TIME);
                break;
        }
    }

    private class MyAdapter
            extends
            BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return null == data ? 0 : data.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView == null) {
                view = View.inflate(context, R.layout.om_my_coupon_list_item, null);
            } else {
                view = convertView;
            }
            ImageView ivImg = (ImageView) view.findViewById(R.id.iv_om_my_coupon_list_item);
            TextView tvValue = (TextView) view.findViewById(R.id.tv_om_my_coupon_list_item_value);
            LinearLayout llFromTo = (LinearLayout) view.findViewById(R.id.ll_om_my_coupon_list_item_from_to);
            TextView tvFrom = (TextView) view.findViewById(R.id.tv_om_my_coupon_list_item_from);
            TextView tvTo = (TextView) view.findViewById(R.id.tv_om_my_coupon_list_item_to);
            TextView tvUseTime = (TextView) view.findViewById(R.id.tv_om_my_coupon_list_item_use_time);
            TextView tvStatus = (TextView) view.findViewById(R.id.tv_om_my_coupon_list_item_status);
            ImageView ivOutTime = (ImageView) view.findViewById(R.id.iv_om_my_coupon_list_item_out_time);
            llFromTo.setVisibility(View.VISIBLE);
            tvUseTime.setVisibility(View.GONE);
            ivOutTime.setVisibility(View.GONE);
            ivImg.setBackgroundResource(R.drawable.coupon_icon);
            tvValue.setText(data.get(position).getCardName());
            tvFrom.setText(DateUtil.getDate(data.get(position).getValidityStartTime()));
            tvTo.setText(DateUtil.getDate(data.get(position).getValidityEndTime()));
            tvUseTime.setText("使用时间：" + DateUtil.getDate(data.get(position).getUseTime()));
            switch (data.get(position).getStatus()) {
                case 1:
                    ivImg.setAlpha(1.0f);
                    tvValue.setTextColor(Color.parseColor("#323232"));
                    tvStatus.setTextColor(Color.parseColor("#ff9600"));
                    tvStatus.setText("未使用");
                    if (data.get(position).getValidityEndTime() - System.currentTimeMillis() <= 5 * 24 * 60 * 60 * 1000) {
                        ivOutTime.setVisibility(View.VISIBLE);
                    }
                    break;
                case 2:
                    ivImg.setAlpha(1.0f);
                    tvValue.setTextColor(Color.parseColor("#323232"));
                    tvStatus.setTextColor(Color.parseColor("#323232"));
                    tvStatus.setText("已使用");
                    llFromTo.setVisibility(View.GONE);
                    tvUseTime.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    ivImg.setAlpha(0.5f);
                    tvValue.setTextColor(Color.parseColor("#c6c6c6"));
                    tvStatus.setTextColor(Color.parseColor("#c6c6c6"));
                    tvStatus.setText("已过期");
                    break;
                default:
                    ivImg.setAlpha(1.0f);
                    tvValue.setTextColor(Color.parseColor("#323232"));
                    tvStatus.setTextColor(Color.parseColor("#ff9600"));
                    tvStatus.setText("未使用");
                    break;
            }
            return view;
        }

    }

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!existMainActivity()) {
            startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
        }
    }
}
